package com.example.demo.niuke;

/**
 * @Author: liull
 * @Description: 获取一个字符串在另一个字符串中出现的次数
 * 例如  “ab” 在“abkjkjjjjdajabhhabbab”
 * @Date: Created in 19:30 2020/3/28
 * @Modified By:
 */
public class Main38 {
    public static void main(String[] args) {
        String s1 = "ab";
        String s2 = "abkjkjjjjdajabhhabbab";
        System.out.println(getCount(s1, s2));
        System.out.println(getCount1(s1, s2));
    }

    public static int getCount(String s, String t) {
        if (!t.contains(s)) {
            return 0;
        }
        int length = s.length();
        int count = 0;
        for (int i = 0; i < t.length() - length + 1; i++) {
            String s1 = t.substring(i, i + length);
            if (s1.equals(s)) {
                count++;
            }
        }
        return count;
    }

    public static int getCount1(String s, String t) {
        int count = 0;
        while (t.indexOf(s) != -1) {
            count++;
            t = t.replaceFirst(s, "");
        }
        return count;
    }
}
